#include "FileTransfer.h"

void send_file(int client_socket_fd, const char *file_path)
{
    FILE *file = fopen(file_path, "rb");
    if (file == NULL) {
        char error_message[100];
        sprintf(error_message, "无法打开文件：%s", file_path);
        send(client_socket_fd, error_message, strlen(error_message), 0);
        return;
    }

    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    char size_message[100];
    sprintf(size_message, "FILE_SIZE %ld", file_size);
    send(client_socket_fd, size_message, strlen(size_message), 0);

    char buffer[1024];
    while (!feof(file)) {
        size_t bytes_read = fread(buffer, 1, sizeof(buffer), file);
        send(client_socket_fd, buffer, bytes_read, 0);
    }

    fclose(file);

}

void receive_file(int client_socket_fd, const char *save_path)
{
    char buffer[1024];
    int bytes_received = recv(client_socket_fd, buffer, sizeof(buffer) - 1, 0);
    if (bytes_received <= 0) {
        perror("接收错误");
        return;
    }

    if (strncmp(buffer, "FILE_SIZE ", 10)!= 0) {
        perror("错误的文件大小消息格式");
        return;
    }

    long file_size;
    sscanf(buffer + 10, "%ld", &file_size);

    FILE *file = fopen(save_path, "wb");
    if (file == NULL) {
        char error_message[100];
        sprintf(error_message, "无法创建文件：%s", save_path);
        send(client_socket_fd, error_message, strlen(error_message), 0);
        return;
    }

    long bytes_received_total = 0;
    while (bytes_received_total < file_size) {
        bytes_received = recv(client_socket_fd, buffer, sizeof(buffer) - 1, 0);
        if (bytes_received <= 0) {
            perror("接收错误");
            fclose(file);
            return;
        }
        fwrite(buffer, 1, bytes_received, file);
        bytes_received_total += bytes_received;
    }

    fclose(file);

}